package com.example.demorabbitmq1.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitForOrderCancelConfig {


    //////////////////////////////针对消息 delay queue////////////////////////////////
    /**
     * 发送到该队列的message会在一段时间后过期进入到delay_process_queue
     * 每个message可以控制自己的失效时间
     */
    public final static String DELAY_QUEUE_MSG_FOR_ORDERCANCEL = "delay_queue_for_orderCancel";

    /**
     * DLX
     */
    public final static String DELAY_EXCHANGE_NAME_FOR_ORDERCANCEL = "delay_exchange_for_orderCancel";


    /**
     * 正常消费的队列
     */
    public final static String PROCESS_QUEUE_FOR_ORDERCANCEL = "process_queue_for_orderCancel";

    /**
     * 正常队列对应的exchange
     */
    public final static String PROCESS_EXCHANGE_NAME_FOR_ORDERCANCEL = "process_exchange_for_orderCancel";


    public static String ROUTING_KEY_FOR_ORDERCANCEL = "delay_for_orderCancel";

    /**
     * 延迟队列 exchange
     *
     * @return
     */
    @Bean
    public DirectExchange delayExchange() {
        return new DirectExchange(DELAY_EXCHANGE_NAME_FOR_ORDERCANCEL);
    }

    @Bean
    public DirectExchange processExchange() {
        return new DirectExchange(PROCESS_EXCHANGE_NAME_FOR_ORDERCANCEL);
    }

    /**
     * 存放延迟消息的队列 最后将会转发给exchange(实际消费队列对应的)
     *
     * @return
     */
    @Bean
    Queue delayQueue4Msg() {
        return QueueBuilder.durable(DELAY_QUEUE_MSG_FOR_ORDERCANCEL)
                .withArgument("x-dead-letter-exchange", PROCESS_EXCHANGE_NAME_FOR_ORDERCANCEL) // DLX，dead letter发送到的exchange
                .withArgument("x-dead-letter-routing-key", ROUTING_KEY_FOR_ORDERCANCEL) // dead letter携带的routing key
                .build();
    }

    @Bean
    public Queue processQueue() {
        return QueueBuilder.durable(PROCESS_QUEUE_FOR_ORDERCANCEL)
                .build();
    }

    /**
     * 将延迟队列与exchange绑定，即到达指定时间之后需要转交给queue消费
     *
     * @return
     */
    @Bean
    Binding delayBinding() {
        return BindingBuilder.bind(delayQueue4Msg())
                .to(delayExchange())
                .with(ROUTING_KEY_FOR_ORDERCANCEL);
    }

    @Bean
    Binding queueBinding() {
        return BindingBuilder.bind(processQueue())
                .to(processExchange())
                .with(ROUTING_KEY_FOR_ORDERCANCEL);
    }

    //////////////////////////////delay////////////////////////////////


//	@Bean
//	@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
//	//必须是prototype类型
//	public RabbitTemplate rabbitTemplate() {
//		RabbitTemplate template = new RabbitTemplate(connectionFactory());
//		return template;
//	}
}